package com.wzdigit.wms.wms.task.order;

import com.wzdigit.wms.basic.domain.task.TaskScheduling;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.util.StringUtils;
import com.wzdigit.wms.basic.util.common.CommonString;
import com.wzdigit.wms.basic.util.common.SeparatorString;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnDtlMapper;
import com.wzdigit.wms.wms.task.DefaultSchedulingConfigurer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发货单相关调度任务的业务逻辑 服务类
 * 
 * @author Administrator
 *
 */
@Service
@Slf4j
public class GdnScheduleService {
	
	@Autowired
	private GdnDtlMapper gdnDtlMapper;
	
	@Autowired
	private GdnScheduleDealService gdnScheduleDealService;
	
	@Autowired
	private DefaultSchedulingConfigurer defaultSchedulingConfigurer;
	
	/**
	 * 初始化【发货单相关调度任务的业务逻辑】
	 * @throws Exception 
	 */
	public void initialize(TaskScheduling taskScheduling) throws Exception {
		// 单据类型
		List<String> docTypeList = StringUtils.split(taskScheduling.getDocType(), SeparatorString.SEMICOLON);
		// 工厂组织
		List<String> factoryList = StringUtils.split(taskScheduling.getFactory(), SeparatorString.SEMICOLON);

		// 创建TriggerTask
		TriggerTask triggerTask = new TriggerTask(() -> {
			try {
				allotWhs(taskScheduling.getName(), docTypeList, factoryList);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} , new CronTrigger(taskScheduling.getCron()));

		// 添加任务
		defaultSchedulingConfigurer.addTriggerTask(taskScheduling.getTaskSchedulingId(), taskScheduling.getName(), triggerTask);
	}
	
	/**
	 * 发货单自动分配仓库
	 * @throws Exception 
	 * @throws  
	 */
	public synchronized void allotWhs(String taskName, List<String> docTypeList, List<String> factoryList) {
		log.info("【" + taskName + "】定时任务执行...");
		// 缓存发货单表头
		Map<Long, GdnHeader> gdnHeaderMap = new HashMap<Long, GdnHeader>();
		
		// 默认用户
		String loginName = CommonString.DEFAULT_USER_NAME;
		
		// 当前时间
		Date date = new Date();
		
		// BigDecimal.ZERO
		BigDecimal zero = BigDecimal.ZERO;
		
		// 全新未分库的发货单明细列表
		List<GdnDtl> gdnDtlList = gdnDtlMapper.selectGdnAllotWhsTask(docTypeList, factoryList, 1000);
		for (GdnDtl gdnDtl : gdnDtlList) {
			try {
				// 分配库存操作
				gdnScheduleDealService.allowAlocDeal(taskName, loginName, date, zero, gdnDtl, gdnHeaderMap);
				// 下发拣货操作
				gdnScheduleDealService.createPiacktaskDeal(gdnDtl.getGdnHeaderId(), loginName);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}